package com.nowcoder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.nowcoder.entity.LoginRecord;
import com.nowcoder.mapper.LoginRecordMapper;
import com.nowcoder.service.LoginRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 登录记录表 服务实现类
 * </p>
 *
 * @author cd
 * @since 2021-12-17
 */
@Service
public class LoginRecordServiceImpl extends ServiceImpl<LoginRecordMapper, LoginRecord> implements LoginRecordService {

    @Override
    public int oneLoginRecord(LoginRecord loginRecord) {
        LoginRecord record = baseMapper.selectOne(new QueryWrapper<LoginRecord>().eq("uid", loginRecord.getUid()));
        if (record == null) {
            return baseMapper.insert(loginRecord);
        } else {
            return baseMapper.update(null, new UpdateWrapper<LoginRecord>()
                    .eq("uid", loginRecord.getUid())
                    .set("status", loginRecord.getStatus())
                    .set("token", loginRecord.getToken())
                    .set("expirtion", loginRecord.getExpirtion())
                    .set("ip", "localhost")
                    .set("last_time", record.getLoginTime())
                    .set("login_time", new Date()));
        }
    }

    @Override
    public LoginRecord selectByToken(String token) {
        return baseMapper.selectOne(new QueryWrapper<LoginRecord>().eq("token", token));
    }

    @Override
    public int updateTokenStatus(String token, Integer status) {
        return baseMapper.update(null, new UpdateWrapper<LoginRecord>().eq("token", token).set("status", status));
    }
}
